
package com.elong.common.service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;


public class NIOService {

    private static class Singleton{
        private static final NIOService instance = new NIOService();
    }
    
    private Selector selector;
    
    private NIOService(){

    }
    
    @SuppressWarnings("rawtypes")
    public void service(){
        int nKeys = 0;
        
        try {
            selector = Selector.open();
            ServerSocketChannel ssc = ServerSocketChannel.open();
            InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(),9000);
            ssc.socket().bind(address);
            
            //采用非阻塞方式
            ssc.configureBlocking(false);
            
            //向selector注册channel感兴趣的事件
            SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);
            
            while(true){
                //通过select方法通知我们感兴趣的事件发生了
                nKeys = selector.select();
                //如果有我们感兴趣的时间发生了，它的传回值> 0
                if(nKeys > 0){
                    Set selectedKeys = selector.selectedKeys();
                    Iterator iter = selectedKeys.iterator();
                    while(iter.hasNext()){
                        key = (SelectionKey) iter.next();
                        iter.remove();
                        if(key.isAcceptable()){
                            System.out.println("connect");
                            Socket socket = ((ServerSocketChannel)key.channel()).accept().socket();
                            SocketChannel sc = socket.getChannel();
                            
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ |SelectionKey.OP_WRITE);
                        }
                    }
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            
            e.printStackTrace();
        }
    }
    
    public static NIOService getInstance(){
        return Singleton.instance;
    }
    
    public static void main(String[] args) {
        NIOService.getInstance().service();
    }
    
}
